//
//  cmdmain.m
//  iCodeMac
//
//  Created by Andrew Barry on 29/08/09.
//  Copyright 2009 Barry Computer Services. All rights reserved.
//


#import <Cocoa/Cocoa.h>
#import "jsruntimecore.h"
#import "jvm.h"

int main(int argc, char *argv[]) {
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	jvm *java = [jvm instance];
	NSString *path = @"cmdtest.js";
	
	[java startDirectCompilation:TRUE];
	if (![java compileAddFile:path forProject:nil])
	{
		printf("compilation failed\n");
		exit(1);
	}
	if (![java compileJavascript:@"compiled.m" forProject:nil])
	{
		printf("compilation failed\n");
		exit(1);
	}
	struct LoadedCode *loaded = [java getFullCode];
//	[java dumpLinkMap];
//	printf("compilation successful\n");
	
	void (*proc)(jscontext *cx, jsframe *outer, jsvalue me, jsvalue *args, int argc) = (void *) loaded->code;
	jscontext *ctx = jsnewcontext(50);
	initRuntime(ctx);

	int pos = 0;
	
//	printf("initting context\n");
	unsigned char *linkMap = loaded->linkMap;

	while (linkMap[pos]) {
		int op = linkMap[pos++];
//		printf("op: %d\n", op);
		if (op == 1) {
			int slot = *(int *) (linkMap + pos);
			pos += 4;
			int off = *(int *) (linkMap + pos);
			pos += 4;
			ctx->slots[slot]  = bindFunction(ctx, (void *) (loaded->code + off)); 
//			printf("fn into slot %d\n", slot);

		} else if (op == 2) {
			int slen = *(int *) (linkMap + pos);
			pos += 4;
			
			pos += slen;
			
			int off;
			while (off = *(int *) (linkMap + pos)) {
				pos += 4;
			}
			
			pos += 4;
		} else if (op == 3) {
			int off = *(int *) (linkMap + pos);
			pos += 4;
			double dv = *(double *) (linkMap + pos);
			pos += 8;
			ctx->slots[off] = jsnum(ctx, dv);
			
		} else if (op == 4) {
			int off = *(int *) (linkMap + pos);
			pos += 4;
			int len = *(int *) (linkMap + pos);
			pos += 4;
			unsigned short *strData = (unsigned short *) (linkMap + pos);
			pos += len * 2;
			ctx->slots[off] = jsstrnconst(ctx, strData, len);
		} else if (op == 5) {
			int slen = *(int *) (linkMap + pos);
			pos += 4;
			pos += 4 * slen;
		} else {
			printf("unknown link\n");
			exit(1);
			break;
		}
	}
	
	
	
	proc(ctx, nil, JSVAL_VOID, nil, 0);
	
	[pool release];
}
